package com.github.baichuan.gb32960.utils;

import com.github.baichuan.binary.bytes.Endian;
import io.netty.buffer.ByteBuf;

import java.util.Arrays;
import java.util.Optional;

public class ByteBufHelper {

    public static Optional<Short> readUnsignedByte(ByteBuf buf){
        short value = buf.readUnsignedByte();
        if(value == 0xFE || value == 0xFF){
            return Optional.empty();
        } else {
            return Optional.of(value);
        }
    }

    public static Optional<Integer> readUnsignedShort(ByteBuf buf){
        byte[] word = new byte[2];
        buf.readBytes(word);
        if(Arrays.equals(word, new byte[]{(byte)0xFF, (byte)0xFE})
                || Arrays.equals(word, new byte[]{(byte)0xFF, (byte)0xFF})){
            return Optional.empty();
        } else {
            return Optional.of(Endian.BIG.uint16(word));
        }
    }


    public static Optional<Long> readUnsignedInt(ByteBuf buf){
        byte[] word = new byte[4];
        buf.readBytes(word);
        if(word[0] == (byte)0xFF && word[1] == (byte)0xFF && word[1] == (byte)0xFF
                && (word[3] == (byte)0xFF || word[3] == (byte)0xFE)){
            return Optional.empty();
        } else {
            return Optional.of(Endian.BIG.uint32(word));
        }
    }
}
